import React, { useState, useEffect } from 'react';
import Radio from "antd-mobile/es/radio";
import List from "antd-mobile/es/list";

const { RadioItem } = Radio;
const { Item: ListItem } = List;

const SelectPersionList = (props) => {
  const {
    className,
    dataSource,
    style,
    value, // undefined || [{ label, value }]
    onChange,
    disabled,
    renderExtra,
    getContent,
  } = props;

  const [data,setData] = useState([]);

  const [v, setValue] = useState(value);

  useEffect(() => {
    setData(dataSource);
  }, [JSON.stringify(dataSource)]);

  useEffect(() => {
    setValue(value);
  }, [value]);

  return (
    <div className={className || ''} style={style}>
      { data && data.length ? data.map((item) => {
        const Comp = item.isLeaf ? RadioItem : ListItem;
        const checked = (v || []).some(vItem => vItem.value === item.code);
        return (
          <Comp
            disabled={item.disabled !== undefined ? item.disabled : !!disabled}
            key={item.code}
            checked={checked}
            onClick={() => onChange(item, !checked)}
            extra={renderExtra(item)}
          >
            { getContent(item) }
          </Comp>
        );
      }) : null}
    </div>
  );
}

SelectPersionList.defaultProps = {
  style: {
    width: '100%',
  },
};

export default SelectPersionList;
